﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;
using System.Collections;
using System.IO;
using log4net;

namespace Entangle
{
    /// <summary>
    /// Interaction logic for MessageCrafter.xaml
    /// </summary>
    public partial class MessageCrafter : Window
    {
        ICrypto c;
        private static readonly ILog log = LogManager.GetLogger(typeof(MessageCrafter));

        public MessageCrafter()
        {
            InitializeComponent();
            PopulateComboBox();
            
        }
        public class MessTypeDisp
        {
            public string name;
            public string value;
            public override string ToString()
            {
                return name.ToString();
            }
        }

        private void PopulateComboBox()
        {
            FieldInfo[] fieldInfos = typeof(MessageType).GetFields(BindingFlags.Static | BindingFlags.Public);
            foreach (FieldInfo fi in fieldInfos)
            {
                if (fi.IsLiteral && !fi.IsInitOnly)
                {
                    ComboBoxItem cbi = new ComboBoxItem();
                    MessTypeDisp mtd = new MessTypeDisp();
                    mtd.name = fi.Name;
                    mtd.value = fi.GetValue(null).ToString();
                    cbi.Content = mtd;
                    cmbMessType.Items.Add(cbi);
                }
            }

        }

        private void btnLoadDefault_Click(object sender, RoutedEventArgs e)
        {
                c = Cryptography.Instance;
                brdCraftMessage.IsEnabled = true;
        }

     

        private void txtUserID_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            int a;
            if (!int.TryParse(e.Text, out a))
                e.Handled = true;
        }

        private void btnCraft_Click(object sender, RoutedEventArgs e)
        {
            ComboBoxItem cbi = (ComboBoxItem)(cmbMessType.SelectedItem);
            MessTypeDisp mtd = (MessTypeDisp)(cbi.Content);
            Message m = new Message(txtPayload.Text, mtd.value);

            txtMessage.Text = m.ToXMLString();
            tabMessage.IsEnabled = true;
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            Message m = Message.FromXML(txtMessage.Text);
            Message r = MessageManager.Instance.ProcessMessage(m);
            txtResponse.Text = r.ToXMLString();
            tabMessage.SelectedItem = tabResponse;
            txtRPayload.Text = r.Payload;
        }
    }
}
